/*!
 * Component: components/Index/index
 * License: MIT
 * Created: 2019-12-23 16:18
 */
import { topicApi } from '/api/topic'
import { $event } from '/utils'

Component({
  /**
   * Component properties
   */
  properties: {
    paytoast: { type: Boolean, value: false },
    topic: { type: Object, value: {} },
    isdetail: { type: Boolean, value: false },
    withdraw: { type: Boolean, value: false },
    withdrawnum: { type: Number, value: 0 },
  },

  /**
   * Component initial data [private]
   */
  data: {
    show: false,
  },

  /**
   * lifecycle of component
   */
  lifetimes: {},

  /**
   * Component methods
   */
  methods: {
    besure() {
      this.data.withdraw ? this.withdraw() : this.joinTopic()
    },
    /** 跳转提现 */
    withdraw() {
      wx.navigateTo({
        url: '/mine/withdrawContainer/withdrawContainer',
      })
      this.close()
    },
    /** 加入圈子 */
    async joinTopic() {
      const topic = this.data.topic
      /** 付费圈子的扣费提醒 */
      topicApi
        .followTopic(topic.id)
        .then(() => {
          topic.has_followed = true
          this.close(true)
          $event.emit('after:joinTopic', topic)
          this.data.isdetail
            ? ''
            : wx.navigateTo({ url: `/pages/topic/detail/detail?topicId=${topic.id}` })
        })
        .catch((res) => {
          if (res.data.message === '积分不足') {
            this.setData({
              show: true,
            })
          } else {
            wx.showToast({
              title: '加入失败,稍后重试',
              icon: 'none',
            })
          }
        })
    },
    /** 赚积分 */
    toCurrency() {
      wx.switchTab({
        url: '/pages/currency/currency',
      })
    },
    /** 充值 */
    toRecharge() {
      this.close()
      wx.navigateTo({
        url: '/pages/recharge/recharge',
      })
    },
    /** 关闭弹窗 */
    close(joinTopic = false) {
      const paytoast = false
      const topic = this.data.topic
      joinTopic && $event.emit('erorr:integral', { paytoast, topic })
      this.setData({
        paytoast,
        show: false,
      })
    },
  },
})
